package com.yes.yjj.jdbc;

import java.sql.*;
import java.util.Scanner;

public class AppLogin {
    public static void main(String[] args) throws Exception{
        System.out.print("请输入账号:");
        Scanner scanner = new Scanner(System.in);
        String username = scanner.nextLine();
        System.out.print("请输入密码:");
        String password = scanner.nextLine();
        //System.out.println("username="+username);
        //System.out.println("password="+password);
        //login(username,password);
        loginplus(username,password);
    }
    public static void login(String n,String p)throws Exception{
        System.out.println("username="+n);
        System.out.println("password="+p);
        //这种拼接的SQL存在漏洞
        //如果输入账号为 ' or '1'='1
        //只要输入密码就能登录

        String sql="SELECT id FROM `user` WHERE `username` ='" +n+
                "' AND `password`=MD5('" +p+ "') ";
        System.out.println("组成的sql语句是："+sql);
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost:3306/test?useSSL=false";
        String username="root";
        String password="root";
        Connection connection = DriverManager.getConnection(url, username, password);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        if (resultSet.next()){
            System.out.println("登录成功！");
        }else {
            System.out.println("登录失败！");
        }
    }
    public static void loginplus(String n,String p)throws Exception{
        System.out.println("username="+n);
        System.out.println("password="+p);
        String sql="SELECT id FROM `user` WHERE `username` =? AND `password`=MD5(?) ";
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost:3306/test?useSSL=false";
        String username="root";
        String password="root";
        Connection connection = DriverManager.getConnection(url,username,password);
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,n);
        ps.setString(2,p);
        ResultSet resultSet = ps.executeQuery();
        if(resultSet.next()){
            System.out.println("登录成功！");
        }else{
            System.out.println("登录失败！");
        }


    }
}
